package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.pojo.DtsStorage;
import com.qf.service.DtsStorageService;
import com.qf.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/admin/storage")
public class DtsAdminStorageController {

    @Autowired
    DtsStorageService storageService;

    @PostMapping("/delete")
    public Object delete(@RequestBody DtsStorage storage){
        storageService.delete(storage);
        return ResponseUtil.ok();
    }

    @PostMapping("/update")
    public Object update(@RequestBody DtsStorage storage){
        DtsStorage dtsStorage = storageService.update(storage);
        return ResponseUtil.ok(dtsStorage);
    }

    @PostMapping("/create")
    public Object create(MultipartFile file) throws Exception {
        String name = file.getName();
        String uuid = UUID.randomUUID().toString();
        String key = uuid + name;
        int size = (int)file.getSize();
        byte[] bytes = file.getBytes();
        String type = file.getContentType();
        DtsStorage dtsStorage = storageService.insert(name,key,size,bytes,type);
        return ResponseUtil.ok(dtsStorage);
    }

    @GetMapping("/list")
    public Object storage(
            @RequestParam(value = "page",required = false,defaultValue = "1") Integer page,
            @RequestParam(value = "limit",required = false,defaultValue = "10")Integer limit,
            String sort, String order, String key, String name){

        IPage<DtsStorage> iPage = storageService.queryPage(page,limit,sort,order,key,name);

        Map<String,Object> data = new HashMap<>();
        data.put("total",iPage.getTotal());
        data.put("items",iPage.getRecords());
        return ResponseUtil.ok(data);
    }
}
